﻿using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Parser;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GBT.Client.Forms
{
    public partial class PDFToDocument : Form
    {
        public PDFToDocument()
        {
            InitializeComponent();
        }

        List<string> filePaths = new List<string>();

        private void PDFToDocument_Load(object sender, EventArgs e)
        {
            btnSaveExcel.Enabled = false;
            btnSavePowerPoint.Enabled = false;
        }

        private List<StringBuilder> GetPDFDocumentContent()
        {
            List<StringBuilder> stringBuilders = new List<StringBuilder>();
            foreach (string filePath in filePaths)
            {
                if (statusStrip1.InvokeRequired)
                {
                    statusStrip1.Invoke(new Action(delegate
                    {
                        tsslMessage.Text = "Converting file：" + filePath;
                    }));
                }
                StringBuilder result = new StringBuilder();
                using (PdfReader reader = new PdfReader(filePath))
                {
                    var pdfDocument = new PdfDocument(reader);
                    int n = pdfDocument.GetNumberOfPages();

                    for (int i = 1; i <= n; i++)
                    {
                        if (statusStrip1.InvokeRequired)
                        {
                            statusStrip1.Invoke(new Action(delegate
                            {
                                tsslMessage.Text = "Converting file：" + filePath + "，" + i.ToString() + " Page";
                            }));
                        }
                        var page = pdfDocument.GetPage(i);

                        if (page == null)
                        {
                            break;
                        }

                        result.Append(PdfTextExtractor.GetTextFromPage(page));
                    }
                }
                stringBuilders.Add(result);
            }
            return stringBuilders;
        }

        private void PDFConverter(Action action)
        {
            CancellationTokenSource ts = new CancellationTokenSource();
            CancellationToken c = ts.Token;
            Task.Run(action, c).ContinueWith(t =>
            {
                if (btnSaveExcel.InvokeRequired)
                {
                    if (statusStrip1.InvokeRequired)
                    {
                        statusStrip1.Invoke(new Action(delegate
                        {
                            tsslMessage.Text = "Ready";
                        }));
                    }
                    btnSaveExcel.Invoke(new Action(delegate
                    {
                        btnSaveText.Enabled = true;
                        btnSaveWord.Enabled = true;
                        //btnSavePowerPoint.Enabled = true;
                        //btnSaveExcel.Enabled = true;
                    }));
                }
            }, c);

            c.Register(() =>
            {
                //当全部Task终止之后，请在此处逐一终止全部的线程
            });

            tsslMessage.Text = "Ready";
        }

        private void PDF2TEXT()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "(*.txt)|*.txt";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                List<StringBuilder> stringBuilders = new List<StringBuilder>();
                Action action = () =>
                {
                    stringBuilders = GetPDFDocumentContent();
                    if (statusStrip1.InvokeRequired)
                    {
                        statusStrip1.Invoke(new Action(delegate
                        {
                            tsslMessage.Text = "Save as a text file···";
                        }));
                    }
                    foreach (StringBuilder file in stringBuilders)
                    {

                        FileStream sw = File.Open(saveFileDialog.FileName, FileMode.OpenOrCreate);
                        sw.Write(Encoding.UTF8.GetBytes(file.ToString()));
                        sw.Close();
                    }
                };
                PDFConverter(action);
            }
        }

        private void PDF2WORD()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "(*.docx)|*.docx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                List<StringBuilder> stringBuilders = new List<StringBuilder>();
                Action action = () =>
                {
                    stringBuilders = GetPDFDocumentContent();
                    if (statusStrip1.InvokeRequired)
                    {
                        statusStrip1.Invoke(new Action(delegate
                        {
                            tsslMessage.Text = "Save as a word file···";
                        }));
                    }
                    foreach (StringBuilder file in stringBuilders)
                    {
                        XWPFDocument document = new XWPFDocument();

                        string[] paragraphs = file.ToString().Split("\n");
                        foreach (string str in paragraphs)
                        {
                            XWPFParagraph p1 = document.CreateParagraph();
                            XWPFRun r1 = p1.CreateRun();
                            r1.SetText(str.ToString());
                        }

                        FileStream sw = File.Create(saveFileDialog.FileName);
                        document.Write(sw);
                        sw.Close();
                        document.Close();
                    }

                };
                PDFConverter(action);
            }
        }

        private void PDF2EXCEL()
        {
            MessageBox.Show("coming soon！！！");

            Action action = () => { };

            PDFConverter(action);
        }

        private void PDF2POWERPOINT()
        {
            MessageBox.Show("coming soon！！！");

            Action action = () => { };

            PDFConverter(null);
        }

        private void PDF2DOCUMENT(string type)
        {
            if (filePaths.Any())
            {
                btnSaveExcel.Enabled = false;
                btnSaveWord.Enabled = false;
                btnSavePowerPoint.Enabled = false;
                btnSaveText.Enabled = false;

                switch (type)
                {
                    case "excel":
                        PDF2EXCEL();
                        break;
                    case "word":
                        PDF2WORD();
                        break;
                    case "powerpoint":
                        PDF2POWERPOINT();
                        break;
                    case "text":
                        PDF2TEXT();
                        break;
                }
            }
            else
            {
                MessageBox.Show("Please drag and drop or select the file！！！");
            }
        }

        private void btnSaveText_Click(object sender, EventArgs e)
        {
            PDF2DOCUMENT("text");
        }

        private void btnSaveWord_Click(object sender, EventArgs e)
        {
            PDF2DOCUMENT("word");
        }

        private void btnSaveExcel_Click(object sender, EventArgs e)
        {
            PDF2DOCUMENT("excel");
        }

        private void btnSavePowerPoint_Click(object sender, EventArgs e)
        {
            PDF2DOCUMENT("powerpoint");
        }

        private void lvPDFileList_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        private void lvPDFileList_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
                foreach (string filePath in filePaths)
                {
                    if (filePath.Contains(".pdf"))
                    {
                        this.filePaths.Add(filePath);
                        lvPDFileList.Items.Add(filePath);
                    }
                }
            }
        }
    }
}
